<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加' : '编辑配置'"
    width="60%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="选择类型" prop="type">
        <ElSelect v-model="formData.type">
          <ElOption label="字符串类型" value="1" />
          <ElOption label="开关类型" value="2" />
          <ElOption label="图片类型" value="3" />
        </ElSelect>
      </ElFormItem>

      <ElRow :gutter="24">
        <ElCol :span="9">
          <ElFormItem label="key值" prop="key">
            <ElInput v-model="formData.key" placeholder="请输入key值" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="9">
          <ElFormItem label="参数名" prop="name">
            <ElInput v-model="formData.name" placeholder="请输入参数名" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="6">
          <ElFormItem label="状态" prop="status">
            <ElSelect v-model="formData.status">
              <ElOption label="开启" value="1" />
              <ElOption label="关闭" value="0" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElFormItem v-if="String(formData.type) === '1'" label="值" prop="value">
        <ElInput v-model="formData.value" placeholder="请输入值" />
      </ElFormItem>

      <ElFormItem v-else-if="String(formData.type) === '2'" label="值" prop="value">
        <ElSelect v-model="formData.value">
          <ElOption label="开启" value="1" />
          <ElOption label="关闭" value="0" />
        </ElSelect>
      </ElFormItem>

      <ElFormItem v-else-if="String(formData.type) === '3'" label="图片" prop="value">
        <ImageSelector v-model="formData.value" :multiple="false" />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import ImageSelector from '@/components/image-selector/index.vue'
  import { addConfigApi } from '@/api/common'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ref, reactive, computed, watch, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'

  interface Props {
    visible: boolean
    type: string
    userData?: Partial<any>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  const formRef = ref<FormInstance>()

  const formData = reactive({
    id: '',
    name: '',
    status: '1',
    type: '1',
    key: '',
    value: ''
  })

  const rules: FormRules = {
    name: [
      { required: true, message: '请输入参数名', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    key: [
      { required: true, message: '请输入 key', trigger: 'blur' },
      { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
    value: [
      { required: true, message: '请输入值', trigger: 'blur' },
      { min: 1, max: 500, message: '长度在 1 到 500 个字符', trigger: 'blur' }
    ]
  }

  /** 初始化表单 */
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.userData
    const row = props.userData
    if (isEdit && row) {
      Object.assign(formData, {
        id: row.id ?? '',
        name: row.name ?? '',
        status: String(row.status ?? '1'),
        type: String(row.type ?? '1'),
        key: row.key ?? '',
        value: row.value ?? ''
      })
    } else {
      Object.assign(formData, {
        id: '',
        name: '',
        status: '1',
        type: '1',
        key: '',
        value: ''
      })
    }
  }

  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => formRef.value?.clearValidate())
      }
    },
    { immediate: true }
  )

  // 类型切换时重置 value（避免遗留不匹配数据）
  watch(
    () => formData.type,
    (val, oldVal) => {
      if (val !== oldVal) {
        formData.value = val === '2' ? '1' : '' // 开关默认 '1'
      }
    }
  )

  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      await formRef.value.validate()
    } catch {
      return
    }
    const submitData: any = {
      name: formData.name,
      key: formData.key,
      status: Number(formData.status),
      type: Number(formData.type),
      value: formData.value,
      block: Number(props.userData?.block)
    }

    try {
      if (dialogType.value === 'add') {
        await addConfigApi(submitData)
        ElMessage.success('添加成功')
      }
      dialogVisible.value = false
      emit('submit')
    } catch (e: any) {
      ElMessage.error(e?.message || '操作失败')
    }
  }
</script>

<style scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
</style>
